package com.zjw.socket.demo.starter.core;

import com.zjw.socket.demo.starter.buffer.BufferDispatcher;
import com.zjw.socket.demo.starter.config.ApplicationConfig;
import com.zjw.socket.demo.starter.core.ioc.IOCScope;
import com.zjw.socket.demo.starter.option.ServiceOptionsFactory;
import com.zjw.socket.demo.starter.plugin.PluginDispatcher;
import com.zjw.socket.demo.starter.service.ServiceDispatcher;
import com.zjw.socket.demo.starter.utils.LogUtils;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;

public class TcpSocketServiceVertApplication {

  private static final String TAG = "TcpSocketServiceVertApp";

  public static void run(Class<?> rootClass) {
    Reflector.attachApplication(rootClass);
    /*创建唯一app*/
    Vertx vertx = Vertx.vertx();
    Reflector.attachVertx(vertx);

    /*初始化配置*/
    ApplicationConfig.initConfig();

    /*创建service*/
    NetServer netServer = vertx.createNetServer(ServiceOptionsFactory.createNetServiceOptions());

    /*启动服务*/
    ServiceDispatcher.dispatchService(vertx);

    /*分发Buffer处理器*/
    BufferDispatcher.dispatchBufferHandler(netServer);

    /*处理消息*/
    netServer.connectHandler(BufferDispatcher::dispatchConnect);

    PluginDispatcher.dispatchPlugin();

    if (Reflector.openIOC) {
      IOCScope.globalScope.refresh(Reflector.PROJECT_ROOT_PACKAGE_NAME);
    }

    /*监听*/
    netServer.listen(service -> {
      if (service.succeeded()) {
        LogUtils.debug(TAG, "成功启动");
      } else {
        LogUtils.error(TAG, "失败");
      }
    });
  }
}
